package com.whcoding.test.common.validator;

import com.whcoding.test.annotion.InConstraint;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @program: spring-boot-learning
 * @description:
 * @author: whcoding
 * @create: 2022-08-01 15:40
 **/
@Slf4j
public class InConstraintValidator implements ConstraintValidator<InConstraint, String> {

	private String[] allowed;

	@Override
	public void initialize(InConstraint constraintAnnotation) {
        /*
        constraintAnnotation 里面有注解的信息
         */
		this.allowed = constraintAnnotation.value();
	}

	/**
	 *
	 * @param value value的类型由泛型上面决定，这里是String。可以配置多个类型的校验器
	 * @param context
	 * @return
	 */
	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		for (String str : this.allowed) {
			if (str.equals(value)) {
				return true;
			}
		}
		return false;
	}
}
